package com.jgp.security.shiro;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.apache.shiro.codec.Hex;
import org.apache.shiro.crypto.AesCipherService;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 项目   parent
 * 作者   loufei
 * 时间   2018/4/6
 */
public class AESMatcher extends SimpleCredentialsMatcher {
    
    private boolean devMode;
    private byte[] key;
    private AesCipherService aesCipherService = new AesCipherService();

    public AESMatcher(boolean devMode,String keyFile) throws IOException {
        this.devMode = devMode;
        aesCipherService.setKeySize(128); //设置key长度
        Path keyFilePath = Paths.get(keyFile);
        if(Files.exists(keyFilePath)){
            key = Files.readAllBytes(keyFilePath);
        }else {
            if(Files.isWritable(keyFilePath)){
                throw new IOException("无法将秘钥写入："+keyFile);
            }else {
                key = aesCipherService.generateNewKey().getEncoded();
                Files.write(keyFilePath,key);
            }
        }
    }

    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        String dbPass =
                new String(aesCipherService.decrypt(Hex.decode(info.getCredentials()+""), key).getBytes());
        return this.devMode?true:dbPass.equals(String.valueOf((char[])token.getCredentials()));
    }
    
    public static void main(String[] args) {
        AesCipherService aesCipherService = new AesCipherService();
        aesCipherService.setKeySize(128); //设置key长度
        //生成key
        //Key key = aesCipherService.generateNewKey();
        byte[] key = null;
        try {
            key = Files.readAllBytes(Paths.get("/Volumes/Transcend/jgp_password_aes"));
        } catch (IOException e) {
            e.printStackTrace();
        }
       /* try {
            Files.write(Paths.get("/Volumes/Transcend/jgp_password_aes"),key.getEncoded());
        } catch (IOException e) {
            e.printStackTrace();
        }*/
        String text = "hello";
        //加密
        String encrptText =
                aesCipherService.encrypt(text.getBytes(), key).toHex();
        System.out.println(encrptText);
        String encrptText2 =
                aesCipherService.encrypt(text.getBytes(), key).toHex();
        System.out.println(encrptText2);
        //解密
        String text2 =
                new String(aesCipherService.decrypt(Hex.decode(encrptText), key).getBytes());
    
        System.out.println(text.equals(text2));
    }

}
